package com.ubs.training.web.controller;

import com.ubs.training.server.dao.model.Client;
import com.ubs.training.server.service.ActivityCounter;
import com.ubs.training.server.service.ClientService;
import com.ubs.training.web.util.ClientValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * User: xubuntu
 * Date: 8/21/12
 * Time: 10:58 AM
 * To change this template use File | Settings | File Templates.
 */
@Transactional @Controller
public class ClientController {

    @Autowired
    ActivityCounter counter;

    @Autowired
    ClientService svc;

    @RequestMapping(value = "client/list", method = RequestMethod.GET)
    public String listClients(Model model) {
        model.addAttribute("clients", svc.getAllClients());
        model.addAttribute("counter", counter.getActivityCounter());
        return "listclients";
    }

    @RequestMapping(value = "client/{clientId}/edit", method = RequestMethod.GET)
    public String getClient(@PathVariable("clientId") int clientId, Model model) {
        Client client;
        if(clientId > 0) {
            client = svc.getById(clientId);
        } else {
            client = new Client();
        }
        model.addAttribute("client", client);
        return "editclient";
    }


    @RequestMapping(value = "client/{clientId}/edit", method = RequestMethod.POST)
    public String saveClient(@PathVariable("clientId") int clientId, @ModelAttribute("client") Client client, BindingResult res) {

        new ClientValidator(client, res).validate();
        client.setId(clientId);
        if(res.hasErrors()) {
            return "editclient";
        }
        svc.saveClient(client);

        counter.trackActivity();

        return "redirect:/client/list.do";
    }

    @RequestMapping(value = "logout.do", method = RequestMethod.GET)
    public String handleLogout(HttpSession session) {
        session.invalidate();
        return "redirect:/";
    }



}
